package com.tange.ai.iot.client.gnssa.play.multi

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.*
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.databinding.ActivityDevicePlaybackMultiChannelBinding
import com.tange.base.toolkit.*
import com.tange.core.media.render.DeviceMediaRender
import com.tange.core.media.source.impl.cloud.CloudStorageMediaSource
import com.tange.core.media.source.impl.cloud.CloudVideoIndex
import com.tg.appcommon.android.TGLog
import com.tg.data.media.AvSyncController

class MultiChannelCloudPlaybackActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "MultiChannelCloudPlaybackActivity_"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"

        fun launch(context: Context, deviceId: String) {
            context.startActivity(Intent(context, MultiChannelCloudPlaybackActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
            })
        }
    }

    private lateinit var deviceId: String

    private lateinit var binding: ActivityDevicePlaybackMultiChannelBinding

    private lateinit var cloudStorageMediaSource: CloudStorageMediaSource

    private lateinit var deviceMediaRender_1: DeviceMediaRender

    private lateinit var deviceMediaRender_2: DeviceMediaRender

    private var isLandscape = false
    private var rendered = false

    private lateinit var listAdapter: ListAdapter

    private var speedPlayEnabled = false

    private var paused = false
    private  var avSyncController : AvSyncController = AvSyncController()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityDevicePlaybackMultiChannelBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            com.tange.ai.iot.client.gnssa.utils.Utils.setDarkStatusBar(this@MultiChannelCloudPlaybackActivity, Color.TRANSPARENT)
            listAdapter = ListAdapter()
            list.layoutManager = LinearLayoutManager(this@MultiChannelCloudPlaybackActivity, LinearLayoutManager.VERTICAL, false)
            list.adapter = listAdapter
            name.text = "云端录像"
        }

        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)!!

        configureMediaSource()

        // 创建媒体播放器-1
        configureRender_1()

        // 创建媒体播放器-2
        configureRender_2()

        binding.loading.visible()
        binding.audio.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_volume_on_24))
        binding.audio.onClicked { switchAudio() }
        binding.back.onClicked { finish() }
        binding.connect.onClicked {  }

        configureDateFilter()

        queryCloudPlayback(DateUtil.getTodayDate())
    }

    private fun configureDateFilter() {
        binding.days.visible()

        binding.day3.text = DateUtil.getTodayDate()
        binding.day3.tag = DateUtil.getTodayDate()

        binding.day1.text = DateUtil.getOldDate(-2)
        binding.day1.tag = DateUtil.getOldDate(-2)

        binding.day2.text = DateUtil.getOldDate(-1)
        binding.day2.tag = DateUtil.getOldDate(-1)

        binding.day3.onClicked {
            queryCloudPlayback(it.tag.toString())
            binding.day1.setBackgroundColor(ContextCompat.getColor(it.context, R.color.green))
            binding.day2.setBackgroundColor(ContextCompat.getColor(it.context, R.color.green))
            binding.day3.setBackgroundColor(
                ContextCompat.getColor(
                    it.context,
                    com.tange.base.ui.design.featured.R.color.basic_color_brand_0
                )
            )
        }

        binding.day2.onClicked {
            queryCloudPlayback(it.tag.toString())
            binding.day1.setBackgroundColor(ContextCompat.getColor(it.context, R.color.green))
            binding.day2.setBackgroundColor(
                ContextCompat.getColor(
                    it.context,
                    com.tange.base.ui.design.featured.R.color.basic_color_brand_0
                )
            )
            binding.day3.setBackgroundColor(ContextCompat.getColor(it.context, R.color.green))
        }

        binding.day1.onClicked {
            queryCloudPlayback(it.tag.toString())
            binding.day1.setBackgroundColor(
                ContextCompat.getColor(
                    it.context,
                    com.tange.base.ui.design.featured.R.color.basic_color_brand_0
                )
            )
            binding.day2.setBackgroundColor(ContextCompat.getColor(it.context, R.color.green))
            binding.day3.setBackgroundColor(ContextCompat.getColor(it.context, R.color.green))
        }
    }

    private fun configureRender_2() {
        deviceMediaRender_2 = DeviceMediaRender(this, cloudStorageMediaSource).apply {

            videoFrameFilter = DeviceMediaRender.MediaFrameFilterByCameraIndex(1)

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer2, createCenterLayoutParams())

            // 监听首帧数据渲染回调
            observeFirstFrameRendered {
                TGLog.i(TAG, "[first-rendered] ")
                rendered = true
                binding.loading.gone()
            }

            enableAudioRender(false)

            enableAudio(false)
            setAvSyncController(avSyncController)
        }
    }

    private fun configureRender_1() {
        deviceMediaRender_1 = DeviceMediaRender(this, cloudStorageMediaSource).apply {

            videoFrameFilter = DeviceMediaRender.MediaFrameFilterByCameraIndex(0)

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer1, createCenterLayoutParams())

            // 监听首帧数据渲染回调
            observeFirstFrameRendered {
                TGLog.i(TAG, "[first-rendered] ")
                rendered = true
                binding.loading.gone()
            }
            setAvSyncController(avSyncController)
        }

        // 监听播放的时间戳更新
        deviceMediaRender_1.onTimestampUpdate = Consumer {
            binding.playTimestamp.post {
                binding.playTimestamp.text = DateUtil.getStrToTime(it)
            }
        }

        // 监听播放状态
        deviceMediaRender_1.renderStatusObserver = object : DeviceMediaRender.RenderStatusObserver {
            override fun onStart() {

            }

            override fun onComplete() {
                binding.playTimestamp.post {
                    binding.playTimestamp.text = "播放完成"
                    paused = false
                }
            }
        }
    }

    private fun configureMediaSource() {
        cloudStorageMediaSource = CloudStorageMediaSource(this, deviceId).apply {
            observeFirstFrameReceived {
                TGLog.i(TAG, "[first-received] ")
            }

            enableVideoProduce(true)
            enableAudioProduce(true)
        }

        // 监听云端数据源的获取状态
        cloudStorageMediaSource.obtainStatusObserver =
            object : CloudStorageMediaSource.ObtainStatusObserver {

                override fun onDataSourceChanged(dataSource: CloudStorageMediaSource.DataSource) {
                    TGLog.i(
                        TAG,
                        "[ObtainStatus-Observer][onDataSourceChanged] ${dataSource.startTime?.asTime()} ----> ${dataSource.endTime?.asTime()}"
                    )
                }

                override fun onStart(time: Long) {
                    TGLog.i(TAG, "[ObtainStatus-Observer][onStart] time = ${time.asTime()}")
                }

                override fun onError(time: Long, code: Int, message: String) {
                    TGLog.i(
                        TAG,
                        "[ObtainStatus-Observer][onError] time = ${time.asTime()}, code = $code, message = $message "
                    )
                    binding.playTimestamp.text = "${time.asTime()} 的云录像丢失"

                }

                override fun onSuccess(time: Long) {
                    TGLog.i(TAG, "[ObtainStatus-Observer][onSuccess] time = ${time.asTime()}")
                    binding.loading.gone()
                }

                override fun onComplete() {
                    TGLog.i(TAG, "[ObtainStatus-Observer][onComplete] ")
                }
            }
    }

    private fun queryCloudPlayback(date: String) {
        TGLog.i(TAG, "[queryCloudPlayback] $date ...")
        CloudVideoIndex(deviceId).query(date) { resp ->

            ui {
                if (resp.success) {
                    if ((resp.data?.size ?: 0) > 0) {
                        resp.data?.let {
                            TGLog.i(TAG, "[queryCloudPlayback][$date] size = ${resp.data?.size ?: 0}")

                            val reversed = it.asReversed()
                            binding.list.visible()
                            binding.list.scrollToPosition(0)
                            listAdapter.refresh(reversed)
                            cloudStorageMediaSource.setDataSource(reversed[0].toDataSource())
                            cloudStorageMediaSource.seek(reversed[0].startTime ?: 0)
                            TGLog.i(TAG, "[queryCloudPlayback][$date] seek ${(reversed[0].startTime ?: 0).asTime()}")
                            TGLog.i(TAG, "[OnSelected] seek to ${(reversed[0].startTime ?: 0).asTime()}")
                            deviceMediaRender_1.reset()
                            deviceMediaRender_2.reset()
                            binding.emptyView.gone()
                        }
                    } else {
                        binding.list.gone()
                        binding.emptyView.visible()
                        binding.emptyView.text = "当日无云录像"
                    }
                } else {
                    if (resp.code == CloudVideoIndex.ERROR_NO_RECORD) {
                        binding.list.gone()
                        binding.emptyView.visible()
                        binding.emptyView.text = "当日无云录像"
                    } else {
                        binding.list.gone()
                        binding.emptyView.visible()
                        binding.emptyView.text = "获取云录像失败 ${resp.code}, ${resp.message}"
                    }

                    binding.loading.gone()
                }
            }

        }
    }

    override fun onResume() {
        super.onResume()
        TGLog.i(TAG, "[onResume] ")
        deviceMediaRender_1.enableVideoRender(true)
        deviceMediaRender_2.enableVideoRender(true)
        deviceMediaRender_2.enableAudioRender(false)
        cloudStorageMediaSource.enableVideoProduce(true)
    }

    override fun onPause() {
        super.onPause()
        TGLog.i(TAG, "[onPause] ")
        deviceMediaRender_1.enableAudioRender(false)
        cloudStorageMediaSource.enableVideoProduce(false)
        cloudStorageMediaSource.enableAudioProduce(false)
        binding.audio.setImageDrawable(ContextCompat.getDrawable(this,
            R.drawable.ic_baseline_volume_off_24
        ))
    }

    private fun createCenterLayoutParams() = FrameLayout.LayoutParams(
        FrameLayout.LayoutParams.MATCH_PARENT,
        FrameLayout.LayoutParams.MATCH_PARENT
    ).apply { gravity = Gravity.CENTER }

    private fun switchAudio() {
        if (cloudStorageMediaSource.isAudioProduceEnabled()) {
            binding.audio.setImageDrawable(ContextCompat.getDrawable(this,
                R.drawable.ic_baseline_volume_off_24
            ))
            cloudStorageMediaSource.enableAudioProduce(false)
            deviceMediaRender_1.enableAudioRender(false)
        } else {
            binding.audio.setImageDrawable(ContextCompat.getDrawable(this,
                R.drawable.ic_baseline_volume_on_24
            ))
            cloudStorageMediaSource.enableAudioProduce(true)
            deviceMediaRender_1.enableAudioRender(true)
        }
    }

    inner class ListAdapter : RecyclerView.Adapter<ViewHolder>() {
        private val apList: MutableList<CloudVideoIndex.Record> = java.util.ArrayList()
        fun refresh(list: List<CloudVideoIndex.Record>) {
            apList.clear()
            apList.addAll(list)
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
            val view: View = LayoutInflater.from(viewGroup.context)
                .inflate(R.layout.item_cloud_record_list, viewGroup, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
            val item = apList[position]
            var msg = ""
            val duration = (item.endTime ?: 0) - (item.startTime ?: 0)
            viewHolder.start.text = "${DateUtil.getStrToTime(item.startTime ?: 0)}  -  ${DateUtil.getStrToTime(item.endTime ?: 0)}   ${duration/1000}s"
            viewHolder.itemView.setOnClickListener { view: View? ->
                Toast.makeText(this@MultiChannelCloudPlaybackActivity, "切换到：${DateUtil.getStrToTime(item.startTime ?: 0)} ...", Toast.LENGTH_LONG).show()
                paused = false
                cloudStorageMediaSource.setDataSource(item.toDataSource())
                cloudStorageMediaSource.seek(item.startTime ?: 0)
                TGLog.i(TAG, "[OnSelected] seek to ${(item.startTime ?: 0).asTime()}")
                deviceMediaRender_1.reset()
                deviceMediaRender_2.reset()
            }
        }

        override fun getItemCount(): Int {
            return apList.size
        }
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val start: TextView

        init {
            start = view.findViewById(R.id.start)
        }
    }
}